/*  
 *  ------ [ZB_09b] - complete example receive  ------
 *  
 *  Explanation: This is a complete example for XBee-ZigBee.
 *  This example shows how to reeive a packet. When the source 
 *  address is the expected one, an answer is sent back to the
 *  emitter Waspmote
 *  
 *  Copyright (C) 2012 Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details. 
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 *  
 *  Version:           0.1 
 *  Design:            David Gascón 
 *  Implementation:    Yuri Carmona
 */


#include <MakeSureXBeeZB.h>
#include <MakeSureFrame.h>

// pointer to the packet to send
packetXBee* packet;
long previous=0;
uint8_t destination[8];
char* MacLow="40A91B00";
char* Mote_ID="Makesure_09b";

String s;
void setup()
{  
  // init Serial port
  Serial.begin(9600);
  Serial.println("ZB_09b complete example");
  
  //////////////////////////
  // 1. init XBee
  //////////////////////////
  xbeeZB.ON();  
  
  delay(3000);
  
  //////////////////////////
  // 2. check XBee's network parameters
  //////////////////////////
  checkNetworkParams();

}


void loop()
{
  // wait message for 20 seconds
  previous=millis();
  while( (millis()-previous) < 20000 )
  {
    // check available data in RX buffer
    if( xbeeZB.available() > 0 ) 
    {
		Serial.print("Data Available");
      // parse information
      xbeeZB.treatData(); 

      // check RX flag after 'treatData'
      if( !xbeeZB.error_RX ) 
      {
        // check available packets
        while( xbeeZB.pos>0 )
        {

			Serial.print("Data: ");             
        for(int i=0;i<xbeeZB.packet_finished[xbeeZB.pos-1]->data_length;i++)          
        {           
          s=String(xbeeZB.packet_finished[xbeeZB.pos-1]->data[i]); 
		  Serial.print(s);
        }
        Serial.println("");

          /*** Available info in 'xbeeZB.packet_finished' structure ***/

          // get Source's MAC address
          destination[0]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[0]; 
          destination[1]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[1]; 
          destination[2]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[2]; 
          destination[3]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[3]; 
          destination[4]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[0]; 
          destination[5]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[1]; 
          destination[6]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[2]; 
          destination[7]=xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[3]; 


          /************ 1.CREATE FRAME  ***************/

          // 1.1. create new frame
          frame.createFrame(ASCII,MacLow,Mote_ID);  

          // 1.2. add frame fields
          frame.addSensor(SENSOR_STR, "Response_message");


          /************  2.SEND PACKET  ***************/

          // 2.1. send response    
          packet=(packetXBee*) calloc(1,sizeof(packetXBee)); 
          packet->mode=UNICAST;                   

          // 2.2. set Destination parameters
          xbeeZB.setDestinationParams(packet, destination, frame.buffer, frame.length);

          // 2.3. send packet
          xbeeZB.sendXBee(packet);

          Serial.print("New packet received. send response: ");

          // 2.4. check TX flag
          if( !xbeeZB.error_TX ) 
          {
            Serial.println("ok");
            Serial.print("true_naD: ");
            Serial.print(packet->true_naD[0],HEX);
            Serial.println(packet->true_naD[1],HEX);

            Serial.print("retries: ");
            Serial.println(packet->retries,HEX);

            Serial.println("---------------");
          }
          else Serial.println("error"); 

		  // 2.5. free memory
          free(packet);
          packet=NULL; 

          // 2.6. free variable 
          free(xbeeZB.packet_finished[xbeeZB.pos-1]);
          xbeeZB.packet_finished[xbeeZB.pos-1]=NULL;

          // 2.7. decrement packet counter
          xbeeZB.pos--; 
        } 
      }
    }
  }/* end while */

  delay(5000);
}





/*******************************************
 *
 *  checkNetworkParams - Check operating
 *  network parameters in the XBee module
 *
 *******************************************/
void checkNetworkParams()
{
  // 1. get operating 64-b PAN ID
  xbeeZB.getOperating64PAN();

  // 2. wait for association indication
  xbeeZB.getAssociationIndication();
 
  while( xbeeZB.associationIndication != 0 )
  {   
    printAssociationState();
   
    delay(2000);
    
    // get operating 64-b PAN ID
    xbeeZB.getOperating64PAN();

    Serial.print("operating 64-b PAN ID: ");
    Serial.print(xbeeZB.operating64PAN[0],HEX);
    Serial.print(xbeeZB.operating64PAN[1],HEX);
    Serial.print(xbeeZB.operating64PAN[2],HEX);
    Serial.print(xbeeZB.operating64PAN[3],HEX);
    Serial.print(xbeeZB.operating64PAN[4],HEX);
    Serial.print(xbeeZB.operating64PAN[5],HEX);
    Serial.print(xbeeZB.operating64PAN[6],HEX);
    Serial.print(xbeeZB.operating64PAN[7],HEX);
    Serial.println();     
    
    xbeeZB.getAssociationIndication();
  }

  Serial.println("\nJoined a network!");

  // 3. get network parameters 
  xbeeZB.getOperating16PAN();
  xbeeZB.getOperating64PAN();
  xbeeZB.getChannel();

  Serial.println("operating 16-b PAN ID: ");
  Serial.print(xbeeZB.operating16PAN[0],HEX);
  Serial.print(xbeeZB.operating16PAN[1],HEX);
  Serial.println();

  Serial.println("operating 64-b PAN ID: ");
  Serial.print(xbeeZB.operating64PAN[0],HEX);
  Serial.print(xbeeZB.operating64PAN[1],HEX);
  Serial.print(xbeeZB.operating64PAN[2],HEX);
  Serial.print(xbeeZB.operating64PAN[3],HEX);
  Serial.print(xbeeZB.operating64PAN[4],HEX);
  Serial.print(xbeeZB.operating64PAN[5],HEX);
  Serial.print(xbeeZB.operating64PAN[6],HEX);
  Serial.print(xbeeZB.operating64PAN[7],HEX);
  Serial.println();

  Serial.println("channel: ");
  Serial.print(xbeeZB.channel,HEX);
  Serial.println();

}




/*******************************************
 *
 *  printAssociationState - Print the state 
 *  of the association flag
 *
 *******************************************/
void printAssociationState()
{
  switch(xbeeZB.associationIndication)
  {
    case 0x00  :  Serial.println(F("Successfully formed or joined a network"));
                  break;
    case 0x21  :  Serial.println(F("Scan found no PANs"));
                  break;    
    case 0x22  :  Serial.println(F("Scan found no valid PANs based on current SC and ID settings"));
                  break;    
    case 0x23  :  Serial.println(F("Valid Coordinator or Routers found, but they are not allowing joining (NJ expired)"));
                  break;    
    case 0x24  :  Serial.println(F("No joinable beacons were found"));
                  break;    
    case 0x25  :  Serial.println(F("Unexpected state, node should not be attempting to join at this time"));
                  break;
    case 0x27  :  Serial.println(F("Node Joining attempt failed"));
                  break;
    case 0x2A  :  Serial.println(F("Coordinator Start attempt failed"));
                  break;
    case 0x2B  :  Serial.println(F("Checking for an existing coordinator"));
                  break;
    case 0x2C  :  Serial.println(F("Attempt to leave the network failed"));
                  break;
    case 0xAB  :  Serial.println(F("Attempted to join a device that did not respond."));
                  break;
    case 0xAC  :  Serial.println(F("Secure join error: network security key received unsecured"));
                  break;
    case 0xAD  :  Serial.println(F("Secure join error: network security key not received"));
                  break;
    case 0xAF  :  Serial.println(F("Secure join error: joining device does not have the right preconfigured link key"));
                  break;
    case 0xFF  :  Serial.println(F("Scanning for a ZigBee network (routers and end devices)"));
                  break;
    default    :  Serial.println(F("Unkown associationIndication"));
                  break;  
  }
}

